﻿using Newtonsoft.Json;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using Oplug.CoolTower.DTO;
using Oplug.Services;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Oplug.CoolTower
{
    public class Utilities
    {
        public static string cfgpath = Application.StartupPath + "\\Config.json";
        public static string LocalCfg = Application.StartupPath + "\\localcfg.json";
        public static string UserID { get; set; }
        public static string UserName { get; set; } = "Admin";
        /// <summary>
        /// 员工工号
        /// </summary>
        public static string EmpID { get; set; }
        public static string CompName { get; set; }
        public static string PreStr { get; set; }
        public static DateTime MinDate = DateTime.Parse("1900-01-01");
        public static string DefConn = "RossLive";
        public DTO.SysConfig GetSysCfg()
        {
            string Cfg = TxtRead(cfgpath);
            return JsonConvert.DeserializeObject<DTO.SysConfig>(Cfg);
        }
        public bool CheckUpdate(string AutoUpdateURL)
        {
            bool result = false;
            try
            {
                string Cfg = TxtRead(AutoUpdateURL + "\\Config.json");
                var ConfigRemote = JsonConvert.DeserializeObject<DTO.SysConfig>(Cfg);
                int VersionRemote = int.Parse(ConfigRemote.Version.Replace(".", ""));
                int VersionLocal = int.Parse(Application.ProductVersion.Replace(".", ""));
                result = VersionRemote > VersionLocal;
            }
            catch
            {
                //Utilities.Message(ex.Message, InfoType.Error);
            }
            return result;
        }
        public void TxtWrite(string path, string contents)
        {
            FileStream fs = new FileStream(path, FileMode.Create);
            StreamWriter sw = new StreamWriter(fs, Encoding.UTF8);
            sw.Write(contents);
            sw.Flush();
            sw.Close();
            fs.Close();
        }
        public string TxtRead(string path)
        {
            FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
            StreamReader sr = new StreamReader(fs, Encoding.UTF8);
            StringBuilder sb = new StringBuilder();
            while (!sr.EndOfStream)
            {
                sb.AppendLine(sr.ReadLine());
            }
            sr.Close();
            return sb.ToString();
        }

        public static T MapTo<T>(object type)
        {
            string jsonText = JsonConvert.SerializeObject(type);
            T obj = JsonConvert.DeserializeObject<T>(jsonText);
            return obj;
        }

        public string Timestamp()
        {
            return (DateTime.Now.Hour * 3600 + DateTime.Now.Minute * 60 + DateTime.Now.Second).ToString();
        }

        public DataTable ListToDataTable<T>(List<T> items, string[] titArr= null, string oldRpChar = "", string newRpChar = "")
        {
            var tb = new DataTable(typeof(T).Name);

            PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
            if (titArr == null)
            {
                foreach (PropertyInfo prop in props)
                {
                    Type t = GetCoreType(prop.PropertyType);
                    if (!string.IsNullOrEmpty(oldRpChar) && !string.IsNullOrEmpty(newRpChar))
                    {
                        tb.Columns.Add(prop.Name.Replace(oldRpChar, newRpChar), t);
                    }
                    else
                        tb.Columns.Add(prop.Name, t);
                }
            }
            else
            {
                foreach (string tit in titArr)
                {
                    tb.Columns.Add(tit);
                }
            }

            foreach (T item in items)
            {
                var values = new object[props.Length];

                for (int i = 0; i < props.Length; i++)
                {
                    values[i] = props[i].GetValue(item, null);
                }

                tb.Rows.Add(values);
            }

            return tb;
        }
        public Type GetCoreType(Type t)
        {
            if (t != null && IsNullable(t))
            {
                if (!t.IsValueType)
                {
                    return t;
                }
                else
                {
                    return Nullable.GetUnderlyingType(t);
                }
            }
            else
            {
                return t;
            }
        }
        public bool IsNullable(Type t)
        {
            return !t.IsValueType || (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>));
        }

        public DataTable DgvToTable(DataGridView dgv)
        {
            DataTable dt = new DataTable();

            // 列强制转换  
            for (int count = 0; count < dgv.Columns.Count; count++)
            {
                DataColumn dc = new DataColumn(dgv.Columns[count].HeaderText.ToString());
                dt.Columns.Add(dc);
            }

            // 循环行  
            for (int count = 0; count < dgv.Rows.Count; count++)
            {
                DataRow dr = dt.NewRow();
                for (int countsub = 0; countsub < dgv.Columns.Count; countsub++)
                {
                    var cell = dgv.Rows[count].Cells[countsub];
                    if (cell.ValueType == typeof(int))
                        dr[countsub] = CInt(cell.Value);
                    else if (cell.ValueType == typeof(decimal) || cell.ValueType == typeof(float) || cell.ValueType == typeof(double))
                        dr[countsub] = CDoub(cell.Value);
                    else
                        dr[countsub] = Convert.ToString(cell.Value);
                }
                dt.Rows.Add(dr);
            }
            return dt;
        }
        public void ExportToExcel(DataGridView dgv, string fileName = "", string filePath = "")
        {
            if (dgv == null)
            {
                return;
            }
            else
            {
                try
                {
                    var result = ExportExcel(dgv, filePath, fileName);
                    if (result != null)
                    {
                        System.Diagnostics.Process.Start(result);
                    }
                }
                catch (Exception err)
                {
                    Utilities.Message(err.Message, InfoType.Error);
                }
            }
        }

        public string ExportExcel(DataTable dt, string filePath, string fileName = "",string dateformat = "yyyy-MM-dd")
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = GetSaveFilePath(fileName);
            }
            if (string.IsNullOrEmpty(filePath)) return null;
            try
            {
                //创建Excel文件的对象  
                NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                int pageSize = 60000;
                int sheetNum = dt.Rows.Count / pageSize;
                if (dt.Rows.Count % pageSize > 0)
                    sheetNum = sheetNum + 1;

                for (int k = 1; k <= sheetNum; k++)
                {
                    NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet" + k);
                    NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
                    for (int i = 0; i < dt.Columns.Count; i++)
                    {
                        row1.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
                    }

                    int startIndex = (k - 1) * pageSize;
                    startIndex = k == 1 ? startIndex : startIndex + 1;

                    int endIndex = k * pageSize;
                    endIndex = endIndex > dt.Rows.Count ? dt.Rows.Count : endIndex;

                    int rowStart = startIndex;
                    for (int i = 0; i < endIndex - startIndex; i++)
                    {
                        NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                        for (int j = 0; j < dt.Columns.Count; j++)
                        {
                            if (dt.Columns[j].DataType == typeof(double) || dt.Columns[j].DataType == typeof(decimal) || dt.Columns[j].DataType == typeof(float) )
                                rowtemp.CreateCell(j).SetCellValue(CDoub(dt.Rows[rowStart][j]));
                            else if (dt.Columns[j].DataType == typeof(int) || dt.Columns[j].DataType == typeof(long))
                                rowtemp.CreateCell(j).SetCellValue(CInt(dt.Rows[rowStart][j]));
                            else if (dt.Columns[j].DataType == typeof(DateTime))
                                rowtemp.CreateCell(j).SetCellValue(CDate(dt.Rows[rowStart][j]).ToString(dateformat).Trim());
                            else
                                rowtemp.CreateCell(j).SetCellValue(dt.Rows[rowStart][j].ToString().Trim());
                        }
                        rowStart++;
                    }
                }

                //NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
                //NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
                //for (int i = 0; i < dt.Columns.Count; i++)
                //{
                //    row1.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
                //}
                //for (int i = 0; i < dt.Rows.Count; i++)
                //{
                //    NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                //    for (int j = 0; j < dt.Columns.Count; j++)
                //    {
                //        rowtemp.CreateCell(j).SetCellValue(dt.Rows[i][j].ToString().Trim());
                //    }
                //}
                // 写入到客户端   
                //MemoryStream ms = new MemoryStream();
                //book.Write(ms);
                //ms.Seek(0, SeekOrigin.Begin);

                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                book.Write(fs);
                fs.Dispose();
                book = null;
            }
            catch (Exception err)
            {
                Utilities.Message(err.Message, InfoType.Error);
            }
            return filePath;
        }

        public string ExportExcel(DataGridView dgv, string filePath, string fileName = "", string dateformat = "yyyy-MM-dd")
        {
            if (string.IsNullOrEmpty(filePath))
            {
                filePath = GetSaveFilePath(fileName);
            }
            if (string.IsNullOrEmpty(filePath)) return null;
            try
            {
                //创建Excel文件的对象  
                NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
                int pageSize = 60000;
                int sheetNum = dgv.Rows.Count / pageSize;
                if (dgv.Rows.Count % pageSize > 0)
                    sheetNum = sheetNum + 1;

                for (int k = 1; k <= sheetNum; k++)
                {
                    NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet" + k);
                    NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
                    for (int i = 0; i < dgv.Columns.Count; i++)
                    {
                        row1.CreateCell(i).SetCellValue(dgv.Columns[i].HeaderCell.Value.ToString());
                    }

                    int startIndex = (k - 1) * pageSize;
                    startIndex = k == 1 ? startIndex : startIndex + 1;

                    int endIndex = k * pageSize;
                    endIndex = endIndex > dgv.Rows.Count ? dgv.Rows.Count : endIndex;

                    int rowStart = startIndex;
                    for (int i = 0; i < endIndex - startIndex; i++)
                    {
                        NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1);
                        for (int j = 0; j < dgv.Columns.Count; j++)
                        {
                            if (dgv.Rows[rowStart].Cells[j].Value != null)
                            {
                                if (dgv.Columns[j].ValueType == typeof(double) || dgv.Columns[j].ValueType == typeof(decimal) || dgv.Columns[j].ValueType == typeof(float))
                                    rowtemp.CreateCell(j).SetCellValue(CDoub(dgv.Rows[rowStart].Cells[j].Value));
                                else if (dgv.Columns[j].ValueType == typeof(double?) || dgv.Columns[j].ValueType == typeof(decimal?) || dgv.Columns[j].ValueType == typeof(float?))
                                    rowtemp.CreateCell(j).SetCellValue(CDoub(dgv.Rows[rowStart].Cells[j].Value));
                                else if (dgv.Columns[j].ValueType == typeof(int) || dgv.Columns[j].ValueType == typeof(long) || dgv.Columns[j].ValueType == typeof(int?) || dgv.Columns[j].ValueType == typeof(long?))
                                    rowtemp.CreateCell(j).SetCellValue(CInt(dgv.Rows[rowStart].Cells[j].Value));
                                else if (dgv.Columns[j].ValueType == typeof(DateTime) || dgv.Columns[j].ValueType == typeof(DateTime?))
                                    rowtemp.CreateCell(j).SetCellValue(CDate(dgv.Rows[rowStart].Cells[j].Value).ToString(dateformat).Trim());
                                else
                                    rowtemp.CreateCell(j).SetCellValue(dgv.Rows[rowStart].Cells[j].Value.ToString().Trim());
                            }
                        }
                        rowStart++;
                    }
                }

                FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                book.Write(fs);
                fs.Dispose();
                book = null;
            }
            catch (Exception err)
            {
                Utilities.Message(err.Message, InfoType.Error);
            }
            return filePath;
        }

        private static string GetSaveFilePath(string fileName = "")
        {
            SaveFileDialog saveFileDig = new SaveFileDialog();
            saveFileDig.Filter = "Excel Office97-2003(*.xls)|.xls|Excel Office2007及以上(*.xlsx)|*.xlsx";
            saveFileDig.FilterIndex = 0;
            saveFileDig.OverwritePrompt = true;
            saveFileDig.InitialDirectory = "C:\\";
            saveFileDig.FileName = fileName; //默认文件名
            string filePath = null;
            if (saveFileDig.ShowDialog() == DialogResult.OK)
            {
                filePath = saveFileDig.FileName;
            }

            return filePath;
        }
        public static string CStr(object val)
        {
            try
            {
                return val.ToString();
            }
            catch { return ""; }
        }
        public static decimal CDec(object val)
        {
            try {
                return Convert.ToDecimal(val);
            } catch { return 0; }
        }
        public static double CDoub(object val)
        {
            try
            {
                return Convert.ToDouble(val);
            }
            catch { return 0; }
        }
        public static int CInt(object val)
        {
            try
            {
                return Convert.ToInt32(val);
            }
            catch { return 0; }
        }
        public static DateTime CDate(object val)
        {
            try
            {
                return Convert.ToDateTime(val);
            }
            catch { return DateTime.Now; }
        }

        public DataTable SqlQuery(Database db, string sql)
        {
            SqlConnection conn = new SqlConnection();
            conn.ConnectionString = db.Connection.ConnectionString;
            if (conn.State != ConnectionState.Open)
            {
                conn.Open();
            }
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = conn;
            cmd.CommandText = sql;
            SqlDataAdapter adapter = new SqlDataAdapter(cmd);
            DataTable table = new DataTable();
            adapter.Fill(table);
            conn.Close();
            conn.Dispose();
            return table;
        }

        public DataSet Query(Database db, string sql)
        {
            SqlConnection con = new SqlConnection(db.Connection.ConnectionString);
            con.Open();
            SqlCommand sqlcmd = new SqlCommand();
            sqlcmd.Connection = con;
            sqlcmd.CommandText = sql;
            SqlDataAdapter sda = new SqlDataAdapter(sqlcmd);
            DataSet data = new DataSet();
            sda.Fill(data);
            return data;
        }
        public static DataTable ExcelToTable(string file)
        {
            DataTable dt = new DataTable();
            IWorkbook workbook;
            string fileExt = Path.GetExtension(file).ToLower();
            using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
            {
                //XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
                if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                if (workbook == null) { return null; }
                ISheet sheet = workbook.GetSheetAt(0);

                //表头  
                IRow header = sheet.GetRow(sheet.FirstRowNum);
                List<int> columns = new List<int>();
                for (int i = 0; i < header.LastCellNum; i++)
                {
                    object obj = GetValueType(header.GetCell(i));
                    if (obj == null || obj.ToString() == string.Empty)
                    {
                        dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
                    }
                    else
                        dt.Columns.Add(new DataColumn(obj.ToString()));
                    columns.Add(i);
                }
                //数据  
                for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
                {
                    DataRow dr = dt.NewRow();
                    bool hasValue = false;
                    foreach (int j in columns)
                    {
                        dr[j] = GetValueType(sheet.GetRow(i).GetCell(j));
                        if (dr[j] != null && dr[j].ToString() != string.Empty)
                        {
                            hasValue = true;
                        }
                    }
                    if (hasValue)
                    {
                        dt.Rows.Add(dr);
                    }
                }
            }
            return dt;
        }

        public IList<T> ExcelToList<T>(string file) where T : class, new()
        {
            IList<T> list = new List<T>();
            try
            {
                IWorkbook workbook;
                string fileExt = Path.GetExtension(file).ToLower();
                using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    if (fileExt == ".xlsx") { workbook = new XSSFWorkbook(fs); } else if (fileExt == ".xls") { workbook = new HSSFWorkbook(fs); } else { workbook = null; }
                    if (workbook == null) { return null; }
                    ISheet sheet = workbook.GetSheetAt(0);

                    IRow header = sheet.GetRow(sheet.FirstRowNum);
                    string[] columns = new string[header.LastCellNum];
                    for (int i = 0; i < header.LastCellNum; i++)
                    {
                        object obj = GetValueType(header.GetCell(i));
                        if (obj == null || obj.ToString() == string.Empty)
                        {
                            columns[i] = "Columns" + i.ToString();
                        }
                        else
                            columns[i] = obj.ToString();
                    }
                    //遍历每一行数据
                    for (int i = sheet.FirstRowNum + 1, len = sheet.LastRowNum + 1; i < len; i++)
                    {
                        T t = new T();
                        IRow row = sheet.GetRow(i);

                        for (int j = 0, len2 = columns.Length; j < len2; j++)
                        {
                            ICell cell = row.GetCell(j);
                            object cellValue = GetValueType(cell);
                            var prop = typeof(T).GetProperty(columns[j]);
                            string vtype = prop.PropertyType.Name.ToLower();
                            if (vtype == "double")
                                prop.SetValue(t, Convert.ToDouble(cellValue), null);
                            else if (vtype == "decimal")
                                prop.SetValue(t, Convert.ToDecimal(cellValue), null);
                            else if (vtype == "int32")
                                prop.SetValue(t, Convert.ToInt32(cellValue), null);
                            else if (vtype == "long")
                                prop.SetValue(t, Convert.ToInt32(cellValue), null);
                            else
                                prop.SetValue(t, cellValue, null);
                        }
                        list.Add(t);
                    }
                }
            }
            catch(Exception ex)
            {
                Message(ex.Message, InfoType.Error);
            }
            return list;
        }
        private static object GetValueType(ICell cell)
        {
            if (cell == null)
                return null;
            switch (cell.CellType)
            {
                case CellType.Blank: //BLANK:  
                    return null;
                case CellType.Boolean: //BOOLEAN:  
                    return cell.BooleanCellValue;
                case CellType.Numeric: //NUMERIC:  
                    return cell.NumericCellValue;
                case CellType.String: //STRING:  
                    return cell.StringCellValue;
                case CellType.Error: //ERROR:  
                    return cell.ErrorCellValue;
                case CellType.Formula: //FORMULA:  
                default:
                    return "=" + cell.CellFormula;
            }
        }

        public static T D2E<T>(DataRow r)
        {
            try {
                T t = default(T);
                t = Activator.CreateInstance<T>();
                PropertyInfo[] ps = t.GetType().GetProperties();
                foreach (var item in ps)
                {
                    if (r.Table.Columns.Contains(item.Name))
                    {
                        object v = r[item.Name];
                        if (v.GetType() == typeof(System.DBNull))
                            v = null;
                        item.SetValue(t, v, null);
                    }
                }
                return t;
            }
            catch { return default(T); }
        }

        public static T D2O<T>(DataRow row)
        {
            T obj = default(T);
            if (row != null)
            {
                obj = Activator.CreateInstance<T>();
                foreach (DataColumn column in row.Table.Columns)
                {
                    PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);
                    try
                    {
                        object value = row[column.ColumnName];
                        prop.SetValue(obj, value, null);
                    }
                    catch { }
                }
            }
            return obj;
        }

        public void SetHeader(DataGridView dgv, string formName)
        {
            string localcfg = TxtRead(Utilities.LocalCfg);
            List<DTO.LocalConfig> LocalCfg = JsonConvert.DeserializeObject<List<DTO.LocalConfig>>(localcfg);
            if (LocalCfg==null) {
                return;
            }
            var cfgs = LocalCfg.Where(o => o.ObjName == formName + "_" + dgv.Name).ToList();
            if (cfgs != null && cfgs.Count > 0)
            {
                int frozenIndex = 0;
                try
                {
                    frozenIndex = cfgs.Where(o => o.IsFrozen == true).OrderByDescending(o => o.FieldIndex).FirstOrDefault().FieldIndex;
                }
                catch { }
                for (int i = 0; i < dgv.Columns.Count; i++)
                {
                    try
                    {
                        var item = cfgs.Where(o => o.FieldName == dgv.Columns[i].Name).FirstOrDefault();                        
                        dgv.Columns[i].ToolTipText = dgv.Columns[i].Name + "(" + i.ToString() + ")";
                        dgv.Columns[i].ReadOnly = item.IsReadOnly;
                        dgv.Columns[i].Visible = !item.IsHidden;
                        dgv.Columns[i].Width = item.FieldWidth;
                        dgv.Columns[i].DisplayIndex = item.FieldDisplayIndex == 0 ? i : item.FieldDisplayIndex;
                        if (!string.IsNullOrEmpty(item.FieldFormat))
                        {
                            dgv.Columns[i].DefaultCellStyle.Format = item.FieldFormat;
                        }
                        dgv.Columns[i].HeaderText = item.FieldDisplay;
                    }
                    catch { }
                }
                dgv.Columns[frozenIndex].Frozen = true;
            }
        }
        public void ExportByDGV(DataGridView dgv)
        {
            try
            {
                //DataTable dt = DgvToTable(dgv);
                ExportToExcel(dgv, "Temp" + DateTime.Now.ToString("yyMMddhhmmss"));
            }
            catch (Exception ex)
            {
                Utilities.Message(ex.Message, InfoType.Error);
            }
        }
        public void DgvSort(List<string> sortList, DataGridView dgv, string sortMod)
        {
            try
            {
                DataTable dt = dgv.DataSource as DataTable;
                DataView dv = dt.DefaultView;
                int columnIndex = dgv.CurrentCell.ColumnIndex;
                string column = dgv.Columns[columnIndex].Name;
                if (!sortList.Exists(s => s == column + " " + sortMod))
                {
                    for (int i = 0; i < sortList.Count; i++)
                    {
                        if (sortList[i].Contains(column))
                        {
                            sortList.RemoveAt(i);
                        }
                    }
                    sortList.Add(column + " " + sortMod);
                }

                string[] array = sortList.ToArray();
                string sortstr = string.Join(",", array);

                dv.Sort = sortstr;
                dgv.DataSource = dv.ToTable();
            }
            catch (Exception ex)
            {
                Utilities.Message(ex.Message, InfoType.Error);
            }
        }
        public void DgvSelect(DataGridView dgv)
        {
            try
            {
                foreach (DataGridViewRow item in dgv.Rows)
                {
                    if (!item.IsNewRow && item.Cells["IsCheck"] != null)
                    {
                        bool isChk= Convert.ToBoolean(item.Cells["IsCheck"].Value) ? false : true;
                        item.Cells["IsCheck"].Value = isChk;
                        item.DefaultCellStyle.BackColor = isChk ? Color.Moccasin : Color.White;
                    }
                }
            }
            catch (Exception ex)
            {
                Utilities.Message(ex.Message, InfoType.Error);
            }
        }
        /// <summary>
        /// 开启DMT
        /// </summary>
        /// <param name="process">开启线程</param>
        /// <param name="exitHandler">结束事件</param>
        /// <param name="excelPath">要导入Excel文档地址</param>
        /// <param name="batName">bat文件名</param>
        /// <param name="dmtMenu">DMT菜单</param>
        /// <param name="act">要执行的DMT动作</param>
        public void StartDMT(System.Diagnostics.Process process, EventHandler exitHandler, string excelPath, string batName, string dmtMenu, bool enableRaisingEvents = true, string act = "-add")
        {
            try
            {
                string batPath = Application.StartupPath + "\\" + batName + ".bat";
                CreateDMTBat(batPath, excelPath, dmtMenu, act);
                //执行BAT文件
                //实例化线程
                process = new System.Diagnostics.Process();
               
                // 指定要运行文件的路径
                process.StartInfo.FileName = batPath;
                //激活Exited
                process.EnableRaisingEvents = enableRaisingEvents;
                if (enableRaisingEvents)
                    //添加结束监视事件
                    process.Exited += new EventHandler(exitHandler);
                //运行程序
                process.Start();
                //if (!enableRaisingEvents)
                //    process.WaitForExit();
            }
            catch (Exception err)
            {
                process = null;
                Utilities.Message(err.Message, InfoType.Error);
            }
        }

        public void CreateDMTBat(string strBatPath, string excelPath, string dmtMenu, string act = "-add")
        {
            if (File.Exists(strBatPath))
            {
                File.Delete(strBatPath);
            }

            var SysConfig = GetSysCfg();

            if (SysConfig != null)
            {

                FileStream fs = new FileStream(strBatPath, FileMode.OpenOrCreate, FileAccess.Write);
                StreamWriter sw = new StreamWriter(fs);
                string strLine;
                strLine = "@ECHO OFF";
                sw.WriteLine(strLine);
                sw.WriteLine("");

                strLine = "ECHO Start "+ dmtMenu+ " "+ act;
                sw.WriteLine(strLine);
                strLine = "start /w " + SysConfig.DBIP + " -environment " + SysConfig.Database + " -user " + SysConfig.DBUser + " -pass " + SysConfig.DBPsw + " -import=\"" + dmtMenu + "\" -source=\"" + excelPath + "\" " + act;
                sw.WriteLine(strLine);
                strLine = "IF %ERRORLEVEL% == 1 ECHO Some Errors While dmt running - review log";
                sw.WriteLine(strLine);
                strLine = "ECHO ..OK";
                sw.WriteLine(strLine);
                sw.WriteLine("");

                strLine = "GOTO END";
                sw.WriteLine(strLine);
                sw.WriteLine("");
                strLine = ":ERROR";
                sw.WriteLine(strLine);
                strLine = "ECHO Error Occured Aborted";
                sw.WriteLine(strLine);
                strLine = "GOTO END";
                sw.WriteLine("");
                sw.WriteLine(strLine);
                strLine = ":END";
                sw.WriteLine(strLine);
                sw.WriteLine("");
                strLine = "ECHO Finished";
                sw.WriteLine(strLine);

                //strLine = "EXIT";
                //sw.WriteLine(strLine);
                sw.Flush();
                sw.Close();
            }
            else
            {
                Utilities.Message("系统配置文件错误，请检查！", InfoType.Error);
            }
        }

        public static string GetIP()
        {
            string _IP = "";
            foreach (System.Net.IPAddress _IPAddress in System.Net.Dns.GetHostEntry(Environment.MachineName).AddressList)
            {
                if (_IPAddress.AddressFamily.ToString() == "InterNetwork")
                { _IP = _IPAddress.ToString(); }
            }
            return _IP;
        }

        public static OutMsg GetViewSQL(string vname, string rossliveconn)
        {
            OutMsg result = new OutMsg();
            result.isValid = false;
            try
            {
                using (DataSQLService ObjServ = new DataSQLService(rossliveconn))
                {
                    var obj = ObjServ.repository.GetAllList(o => o.ViewName == vname).FirstOrDefault();
                    if (obj != null)
                    {
                        result.isValid = true;
                        result.msg = obj.SQLText;
                    }
                }
            }
            catch(Exception ex)
            {
                result.msg = ex.Message;
            }
            return result;
        }

        public string DgvStatistics(DataGridView dgv)
        {
            double sum = 0;
            double max = 0;
            double min = 0;
            double val = 0;
            int count = 0;
            try
            {
                for (int i = 0; i < dgv.Rows.Count; i++)
                {
                    if (dgv.Rows[i].IsNewRow == false)
                    {
                        count++;
                        var Col = dgv.Columns[dgv.CurrentCell.ColumnIndex];
                        if (Col.ValueType == typeof(double) || Col.ValueType == typeof(decimal) || Col.ValueType == typeof(float))
                        {
                            val = Convert.ToDouble(dgv.Rows[i].Cells[dgv.CurrentCell.ColumnIndex].Value);
                            sum += val;
                            if (i == 0)
                            {
                                max = val;
                                min = val;
                            }
                            else
                            {
                                if (val > max)
                                    max = val;
                                if (val < min)
                                    min = val;
                            }
                        }
                    }
                }
            }
            catch (Exception err)
            {
                Utilities.Message(err.Message, InfoType.Error);
            }
            return    "总计：" + count.ToString() 
                    + " 求和：" + sum.ToString()
                    + " 平均值：" + (sum / count).ToString("0.00000")
                    + " 最大值：" + max.ToString()
                    + " 最小值：" + min.ToString();
        }

        static Type[] _assemblyArray;
        readonly static Object lockObject = new Object();
        public Type[] GetAssembly()
        {
            if (_assemblyArray == null)
            {
                lock (lockObject)
                {
                    _assemblyArray = Assembly.GetExecutingAssembly().GetTypes();
                }
            }
            return _assemblyArray;
        }
        public Type[] GetAllForm()
        {
            Type[] assemblyArray = GetAssembly();
            string allType = typeof(Form).FullName;
            return Array.FindAll(assemblyArray, delegate (Type type)
            {
                return (allType == (type.BaseType != null ? type.BaseType.FullName : ""));
            });
        }

        public List<FormMethods> GetAllMethods()
        {
            List<FormMethods> methods = new List<FormMethods>();
            System.Type[] forms = GetAllForm();
            foreach (var item in forms)
            {
                var objs = item.GetRuntimeMethods();
                foreach (MethodInfo o in objs)
                {

                    string methodDesc = "";
                    foreach (object obj in o.GetCustomAttributes(false))
                    {
                        if (obj is DescriptionAttribute)
                        {
                            methodDesc = (obj as DescriptionAttribute).Description;
                        }
                    }
                    methods.Add(new FormMethods
                    {
                        FormName = item.Name,
                        MethodName = o.Name,
                        MethodType = o.DeclaringType.Name,
                        MethodDesc = methodDesc
                    });

                }
            }           
            return methods;
        }

        

        /// <summary>
        /// 系统提示
        /// </summary>
        /// <param name="msg">消息内容</param>
        /// <param name="type">类型：Information、Warn、Error</param>
        public static void Message(string msg, InfoType type = InfoType.Information)
        {
            switch (type)
            {
                case InfoType.Warning:
                    MessageBox.Show(msg, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);                    
                    break;
                case InfoType.Error:
                    MessageBox.Show(msg, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
                default:
                    MessageBox.Show(msg, "消息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    break;
            }
        }
        /// <summary>
        /// 系统确认
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public static DialogResult Confirm(string msg)
        {
            return MessageBox.Show(msg, "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
        }

        
        public void SetNodesColor(TreeNodeCollection node, List<TreeNode> matchNode, Color BackColor, Color foreColor)
        {
            foreach (TreeNode n in node)
            {
                if (matchNode.Contains(n))
                {
                    if (BackColor != null)
                        n.BackColor = BackColor;
                    if (foreColor != null)
                        n.ForeColor = foreColor;
                }
                else
                {
                    n.BackColor = Color.White;
                    n.ForeColor = Color.Black;
                }

                SetNodesColor(n.Nodes, matchNode, BackColor, foreColor);
            }
        }

        public static string EscapeLikeValue(string valueWithoutWildcards)
        {
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < valueWithoutWildcards.Length; i++)
            {
                char c = valueWithoutWildcards[i];
                if (c == '*' || c == '%' || c == '[' || c == ']')
                    sb.Append("[").Append(c).Append("]");
                else if (c == '\'')
                    sb.Append("''");
                else
                    sb.Append(c);
            }
            return sb.ToString();
        }

        public string CvtOper(string opcode, Dictionary<string, string> OpMaster)
        {
            string result = opcode;
            try
            {
                foreach (KeyValuePair<string, string> kv in OpMaster)
                {
                    if (kv.Value.Contains(opcode))
                    {
                        result = kv.Key; break;
                    }
                }
            }
            catch
            {
                result = opcode;
            }
            return result;
        }

        public bool CheckRemoteFile(string fileLocal, string fileRomote)
        {
            if (!string.IsNullOrWhiteSpace(fileLocal) && !string.IsNullOrWhiteSpace(fileRomote))
            {
                var FileRemote = new FileInfo(fileRomote);
                var FileLocal = new FileInfo(fileLocal);
                if (FileRemote.Exists && FileLocal.Exists)
                {
                    return FileLocal.LastWriteTime < FileRemote.LastWriteTime;
                }
                else if (FileRemote.Exists && !FileLocal.Exists)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
                return false;
        }

        public bool CheckReportNew(string CheckUpdateURL)
        {
            bool result = false;
            DirectoryInfo TheFolder = new DirectoryInfo(CheckUpdateURL+ "\\Excel");
            FileInfo[] FileList = TheFolder.GetFiles();
            foreach (FileInfo NextFile in FileList)
            {
                string FileRemote = NextFile.FullName;
                string FileLocal = Application.StartupPath + "\\Excel\\" + NextFile.Name;
                if (CheckRemoteFile(FileLocal, FileRemote))
                {
                    result = true; break;
                }
            }
            return result;
        }

        public string HttpPost(string Url, string body)
        {
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;
            System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(Url);
            request.Method = "POST";
            request.Accept = "text/html, application/xhtml+xml, */*";
            request.ContentType = "application/json";

            byte[] buffer = encoding.GetBytes(body);
            request.ContentLength = buffer.Length;
            request.GetRequestStream().Write(buffer, 0, buffer.Length);
            System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
            using (System.IO.StreamReader reader = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                return reader.ReadToEnd();
            }
        }

        public void setTag(Control cons)
        {
            foreach (Control con in cons.Controls)
            {
                con.Tag = con.Width + ":" + con.Height + ":" + con.Left + ":" + con.Top + ":" + con.Font.Size;
                if (con.Controls.Count > 0)
                    setTag(con);
            }
        }

        public void setControls(float newx, float newy, Control cons)
        {
            foreach (Control con in cons.Controls)
            {

                string[] mytag = con.Tag.ToString().Split(new char[] { ':' });
                float a = Convert.ToSingle(mytag[0]) * newx;
                con.Width = (int)a;
                a = Convert.ToSingle(mytag[1]) * newy;
                con.Height = (int)(a);
                a = Convert.ToSingle(mytag[2]) * newx;
                con.Left = (int)(a);
                a = Convert.ToSingle(mytag[3]) * newy;
                con.Top = (int)(a);
                Single currentSize = Convert.ToSingle(mytag[4]) * Math.Min(newx, newy);
                con.Font = new Font(con.Font.Name, currentSize, con.Font.Style, con.Font.Unit);
                if (con.Controls.Count > 0)
                {
                    setControls(newx, newy, con);
                }
            }
        }

    }
    
    public enum InfoType
    {
        Information,
        Warning,
        Error
    }

}
